import AMapLoader from "@amap/amap-jsapi-loader";

let _AMap = null;

export const initMap = () =>{
    window._AMapSecurityConfig = {
        securityJsCode: "0c966bb01bee5cebdce4a2cdeed7a0bd",
    };
}

export const loadMap = async (elementId) => {
    let map = null;
    await AMapLoader.load({
    key: "8fd3a0a42d52db0451ab70ada1d00401", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Scale", "AMap.Geolocation"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    })
    .then((AMap) => {
        _AMap = AMap
        map = new AMap.Map(elementId, {
        // 设置地图容器id
        viewMode: "3D", // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: [116.397428, 39.90923], // 初始化地图中心点位置
        });
        getCurrentPosition(map)
    })
    .catch((e) => {
        console.log(e);
    });
    return map
}

export const getCurrentPosition = (map) =>{
    _AMap.plugin('AMap.Geolocation', () => {
        let geolocation = new _AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 100000,
            position: 'RB',
            offset: [10, 20],
            zoomToAccuracy: true
        })
        console.log('定位成功')
        map.addControl(geolocation)
        geolocation.getCurrentPosition((status, result)=>{
            if(status == 'complete'){
                changePosition(map, result.position.lng, result.position.lat)
            } else {
                console.log(result, 'eror')
            }
        })
    })
}

export const changePosition = (map, lng, lat, scale = 10) =>{
    map.setCenter([lng, lat])
    map.setZoom(scale)
}

export const addMarker = (map, lng, lat, name, description) =>{
    let marker = new _AMap.Marker({
        position: [lng, lat],
        offset: new _AMap.Pixel(-13, -30),
        content: `<div class="marker" style="width: 300px;"> 
                        <img src="https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png"/>
                        <div style="font-weight: bold;">${name}</div>
                        <div style="">${description}</div>
                  </div>`
    })
    marker.setMap(map)
    return marker
}